"use client";

import { useState, useEffect, useRef } from "react";
import { X, Copy, Check, Download } from "lucide-react";
import QRCode from "react-qr-code";
import { useLanguage } from "@/context/language-provider";

interface QRModalProps {
  isOpen: boolean;
  onClose: () => void;
  url?: string;
}

export default function QRModal({ isOpen, onClose, url }: QRModalProps) {
  const [copied, setCopied] = useState(false);
  const [shareUrl, setShareUrl] = useState("");
  const [qrImageUrl, setQrImageUrl] = useState<string>("");
  const qrRef = useRef<HTMLDivElement>(null);
  const { language, isInternational } = useLanguage();

  useEffect(() => {
    if (url) {
      // 如果是国际版，确保URL中有int=true参数
      if (isInternational && !url.includes('int=true')) {
        const urlObj = new URL(url);
        urlObj.searchParams.append('int', 'true');
        setShareUrl(urlObj.toString());
      } else {
        setShareUrl(url);
      }
    } else {
      // 如果没有提供URL，使用当前页面URL
      const currentUrl = window.location.origin;
      setShareUrl(isInternational ? `${currentUrl}?int=true` : currentUrl);
    }
  }, [url, isInternational]);

  // 处理复制链接
  const handleCopyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("剪贴板写入失败:", err);
      // 降级方案：使用传统方法
      const textArea = document.createElement("textarea");
      textArea.value = shareUrl;
      textArea.style.position = "fixed";  // 避免滚动到底部
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      
      try {
        const successful = document.execCommand("copy");
        if (successful) {
          setCopied(true);
          setTimeout(() => setCopied(false), 2000);
        } else {
          console.error("复制失败");
        }
      } catch (err) {
        console.error("复制过程出错:", err);
      }
      
      document.body.removeChild(textArea);
    }
  };

  // 生成可下载的二维码图片
  const generateQRImage = () => {
    if (!qrRef.current) return;
    
    const svg = qrRef.current.querySelector('svg');
    if (!svg) return;
    
    const svgData = new XMLSerializer().serializeToString(svg);
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();
    
    img.onload = () => {
      canvas.width = img.width;
      canvas.height = img.height;
      if (ctx) {
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);
        
        const pngFile = canvas.toDataURL("image/png");
        setQrImageUrl(pngFile);
      }
    };
    
    img.src = `data:image/svg+xml;base64,${btoa(svgData)}`;
  };

  // 处理二维码下载
  const handleDownloadQR = () => {
    if (qrImageUrl) {
      const downloadLink = document.createElement("a");
      downloadLink.download = "qrcode.png";
      downloadLink.href = qrImageUrl;
      downloadLink.click();
    }
  };

  // 当组件挂载时生成可下载的图片URL
  useEffect(() => {
    if (isOpen && shareUrl) {
      // 在下一个渲染周期后生成图片，确保QR码已渲染
      const timer = setTimeout(() => {
        generateQRImage();
      }, 100);
      
      return () => clearTimeout(timer);
    }
  }, [isOpen, shareUrl]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div 
        className="absolute inset-0 backdrop-blur-sm"
        style={{ backgroundColor: 'hsl(var(--background) / 0.8)' }}
        onClick={onClose}
      />
      <div className="glass-panel w-full max-w-md relative overflow-hidden">
        <div className="border-b p-4 sm:p-5 flex justify-between items-center" style={{ borderColor: 'hsl(var(--border) / 0.4)' }}>
          <h3 className="text-lg font-medium">
            {language === "zh" ? "传递火炬" : "Pass the Torch"}
          </h3>
          <button 
            className="flex items-center justify-center h-8 w-8 rounded-full text-primary"
            style={{ backgroundColor: 'hsl(var(--primary) / 0.1)' }}
            onClick={onClose}
            aria-label={language === "zh" ? "关闭" : "Close"}
          >
            <X className="h-4 w-4" />
          </button>
        </div>
        
        <div className="p-4 sm:p-6 space-y-4">
          <p className="text-sm" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
            {language === "zh" 
              ? "扫描或分享下面的二维码，邀请更多同学加入我们的平台" 
              : "Scan or share the QR code below to invite more students to join our platform"}
          </p>
          
          <div className="flex flex-col gap-6 items-center">
            <div className="bg-white p-3 sm:p-4 rounded-lg shadow-sm relative" ref={qrRef}>
              {qrImageUrl ? (
                <img 
                  src={qrImageUrl} 
                  alt={language === "zh" ? "二维码" : "QR Code"}
                  className="w-[160px] h-[160px]"
                  style={{ 
                    WebkitTouchCallout: "default", 
                    WebkitUserSelect: "auto" 
                  }}
                />
              ) : (
                <QRCode
                  size={160}
                  value={shareUrl}
                  bgColor="#FFFFFF"
                  fgColor="#000000"
                  level="H"
                />
              )}
              {/* <button
                className="absolute -bottom-3 right-1 p-2 rounded-full shadow-sm bg-white border border-primary/30 hover:bg-primary/10 transition-all"
                onClick={handleDownloadQR}
                aria-label="下载二维码"
              >
                <Download className="h-4 w-4 text-primary" />
              </button> */}
            </div>
            <p className="text-xs text-center opacity-70">
              {language === "zh" ? "长按图片或点击下载按钮可保存二维码" : "Long press the image or click the download button to save the QR code"}
            </p>
            <div className="w-full">
              <div className="flex flex-col sm:flex-row">
                <div className="flex-1 rounded-lg sm:rounded-r-none sm:rounded-l-lg p-3 text-sm break-all border sm:border-r-0" style={{
                  backgroundColor: 'hsl(var(--secondary) / 0.3)',
                  borderColor: 'hsl(var(--border) / 0.6)'
                }}>
                  {shareUrl}
                </div>
                <button 
                  className={`mt-2 sm:mt-0 px-3 py-2 sm:py-0 rounded-lg sm:rounded-l-none sm:rounded-r-lg flex items-center justify-center sm:justify-start gap-1.5 text-sm font-medium transition-all border ${
                    copied 
                    ? 'border-green-500/30'
                    : 'border-primary/30 hover:bg-primary/20'
                  }`}
                  style={{
                    backgroundColor: copied ? 'hsla(142, 72%, 29%, 0.2)' : 'hsl(var(--primary) / 0.1)',
                    color: copied ? 'hsl(142, 72%, 29%)' : 'hsl(var(--primary))'
                  }}
                  onClick={handleCopyLink}
                >
                  {copied ? (
                    <>
                      <Check className="h-4 w-4" />
                      {language === "zh" ? "已复制" : "Copied"}
                    </>
                  ) : (
                    <>
                      <Copy className="h-4 w-4" />
                      {language === "zh" ? "复制" : "Copy"}
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 